//
//  MainViewController.swift
//  Weibo
//
//  Created by 梁智 on 15/11/21.
//  Copyright © 2015年 lzfree. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    // MARK: - 监听方法
    @objc private func didClickComposedButton() {
        let vc = UserAccountViewModel.sharedUserAccount.userLogin ? ComposeViewController() : OAuthViewController()
        let nav = UINavigationController(rootViewController: vc)
        presentViewController(nav, animated: true, completion: nil)
    }
    
    // MARK: - 视图生命周期函数
    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
        
        setupComposedButton()
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)
        
        tabBar.bringSubviewToFront(composedButton)
    }
    
    // MARK: - 懒加载控件
    lazy private var composedButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
}

// MARK: - 设置界面
extension MainViewController {
    
    private func setupComposedButton() {
        
        tabBar.addSubview(composedButton)
        
        let count = childViewControllers.count
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        composedButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        
        composedButton.addTarget(self, action: "didClickComposedButton", forControlEvents: .TouchUpInside)
    }
    
    private func addChildViewControllers() {
        
        //tabBar.tintColor = UIColor.orangeColor()
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }

    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        
        vc.title = title
        
        // 设置图片
        vc.tabBarItem.image = UIImage(named: imageName)
        
        // 导航控制器
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
}